<template>
  <div class="UploadImageMutil">
    <template v-if="type == 'default'">

      <a-upload
        :list-type="listType"
        :file-list="fileList"
        multiple
        @preview="handlePreview"
        :customRequest="uploadImage"
        @change="handleChange"
        :before-upload="beforeUpload"
      >
        <div v-if="fileList.length < length">
          <a-icon type="plus" /> <br>
          上传
        </div>
      </a-upload>
      <div class="ant-upload-text" v-html="des">

      </div>

      <a-modal :dialog-style="{ top: '20px' }" :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </template>

    <a-upload-dragger
      v-else-if="type == 'drag'"
      ref="upload"
      :multiple="true"
      :file-list="fileList"
      :customRequest="uploadImage"
      @change="handleChange"
      :before-upload="beforeUpload"
    >
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox" />
      </p>
      <p class="ant-upload-text">
        点击或拖入文件上传
      </p>
    </a-upload-dragger>

    <template v-else-if="type == 'button'">
      <a-upload
        :file-list="fileList"
        :showUploadList="false"
        multiple
        @preview="handlePreview"
        :customRequest="uploadImage"
        @change="handleChange"
        :before-upload="beforeUpload"
      >
        <slot name="btn">
          <a-button type="primary" icon="upload">{{ text || '上传附件' }}</a-button>
        </slot>
      </a-upload>
    </template>
  </div>
</template>

<script>
import { UploadImage } from '@/utils/uploadImage';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  name: 'UploadImageMutil',
  props: {
    des: {
      type: String,
      default: ''
    },
    text: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'default'
    },
    length: {
      type: Number,
      default: 1
    },
    listType: {
      default: 'picture-card',
      type: String
    }
  },
  data() {
    return {
      previewVisible: false,
      imgurl: [],
      fileList: [],
      defaultFileList: [],

      previewImage: ''
    };
  },
  watch: {
    // url: {
    //   handler(e) {
    //     if (e) {

    //     }

    //     //   this.defaultFileList.push(e.split(',').map(e => {
    //     //     return {
    //     //       url: process.env.VUE_APP_UPLOADIMG_URL + e,
    //     //       uid: new Date().getTime(),
    //     //       name: new Date().getTime()
    //     //     };
    //     //   }));
    //     // }
    //   },
    //   deep: true,
    //   immediate: true
    // }

  },
  components: {

  },
  created() {

  },
  mounted() {
    console.log(this.url);
    if (this.url) {
      const fileList = this.url.split(',').map(e => {
        let url = '';
        if (/(http|https):\/\/([\w.]+\/?)\S*/.test(e)) {
          url = e;
        } else {
          url = e;
        }
        return {
            url,
            uid: String(new Date().getTime()),
            name: String(new Date().getTime()),
            status: 'done',
            response: '',
            type: 'image/jpeg'
          };
        });
        if (fileList instanceof Array) {
          this.fileList = fileList;
        }
    } else {
      this.fileList = [];
    }
  },

  methods: {
    setFileList(list) {
      this.fileList = list.map(item => {
        return {
          url: item.url,
          uid: String(new Date().getTime()),
          name: String(new Date().getTime()),
          status: 'done',
          response: '',
          type: 'image/jpeg',
        }
      })
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      console.log(file);
      // if (!file.imgUrl && !file.preview) {
      //   file.preview = await getBase64(file.originFileObj);
      // }
      this.previewImage = file.imgUrl || file.url || file.thumbUrl
      this.previewVisible = true;
    },
    handleChange(info) {
      const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png';
      if (!isJpgOrPng) {
        // this.$message.error('请上传正确的图片格式!');
        return false;
      }

      if (info.file.size > 10 * 1024 * 1024) {
        return false;
      }

      let fileList = [...info.fileList];
      if (fileList.length > this.length) {
        this.$message.error('最多上传' + this.length + '张');
        return;
      }

      fileList = fileList.map(file => {
        if (file.response) {
          file.imgUrl = file.response;
        }
        return file;
      });

      this.fileList = fileList;
      this.imgurl = fileList.filter(file => {
        return file.imgUrl;
      }).map(e => {
        return e.imgUrl;
      }).join(',');
console.log(this.imgurl);
      if (this.imgurl) this.$emit('getUrl', this.imgurl, fileList);
    },
    beforeUpload(file, fileList) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('请上传正确的图片格式!');
        return false;
      }
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error('单张图片大小不能超过10兆!');
        return false;
      }
      return true;
    },
    uploadImage(e) {
      UploadImage(e.file).then(res => {
        e.onSuccess(res.imgUrl);
        // this.$emit('getUrl', res.url);
      }).catch(() => {
        e.onError();
      });
    },
    clear() {
      this.fileList = [];
    }
  }
};
</script>

<style scoped>
  .UploadImageMutil .ant-upload-text {
    line-height: 1.2;
    margin-top: -12px;
  }
</style>
